#include "KPF_DataManager.h"

#include <iostream>
using namespace std;

#include "KPF_StreamServiceSession.h"

#include "log.h"

#include "oal_api.h"

#include "RunTime.h"

class CTestTCPStreamServer : public KPF_StreamServiceSession
{
public:
	CTestTCPStreamServer( const int8_t *pIP, const int16u_t iPort )
		: 	KPF_StreamServiceSession( pIP, iPort )
	{
				
	}
	
	int32_t handle_input( const KPF_Socket *pSocket, const int8u_t *pData, const int32_t iDataLen )
	{
		int32_t iRetCode = -1;
	
		if ( pSocket && pData && iDataLen > 0 )
		{
			fwrite( pData, 1, iDataLen, stdout );
			fflush( stdout );		
		
			iRetCode = ((KPF_Socket *)pSocket)->Send( pData, iDataLen );	
		}
	
		return iRetCode;
	}

	int32_t handle_event( const KPF_Event &eEvent )
	{
		int32_t iRetCode = -1;
	
		if ( EVENT_READ_ERROR == ((KPF_Event)eEvent).getEvent() )
		{
			iRetCode = remove_session_socket( pm_Session, ((KPF_Event)eEvent).getEventParam().pSocket );
		}
		else if ( EVENT_ACCEPT_NEW_STREAM_CLIENT_NOTIFY == ((KPF_Event)eEvent).getEvent() )
		{
			CEventParam *pEventParam = &((KPF_Event)eEvent).getEventParam(  );
		
			if ( net_set_socket( pEventParam->pSocket, SOCKET_OPTION_NONE_BLOCK, NULL, 0 ) >= 0 )
			{
				log_print( (int8_t *)"accept_task: start to add reactor socket................" );
				if ( add_session_socket( pm_Session, pEventParam->pSocket ) >= 0 )
				{
					log_print( (int8_t *)"client:%s:%d", pEventParam->stNetAddr.pIP, pEventParam->stNetAddr.iPort );
				
					iRetCode = net_send( pEventParam->pSocket, (int8u_t *)"welcome\r\n", 9 );
					if ( iRetCode > 0 )
						log_print( (int8_t *)"accept_task: have send %d bytes.", iRetCode );		
				}	
				else 
					log_print( (int8_t *)"accept_task: add reactor socket failed??????????????????????" );		
			}
			else 
				log_print( (int8_t *)"accept_task: set none blocking socket failed????????????????????????" );	
		}
			
		return iRetCode;	
	}
	
protected:

private:

};

int main( int argc, char **argv )
{
	cout<<"main:-------------->"<<endl;
	
	KPF_StreamServiceSession *pStreamServiceSession = new CTestTCPStreamServer( (const int8_t *)"127.0.0.1", 8000 );
	
	if ( pStreamServiceSession )
	{
		pStreamServiceSession->handle_output( pStreamServiceSession->getSocket(  ), NULL, 0 );
	}
	
	while ( 1 )
		os_sleep( 1000 * 1000 * 60 );
		
	return 0;	
}

static CRunTime fg_RunTime;
